package com.xiaochong.tir.manager.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.management.StringValueExp;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;

/**
 * @Author: WangXing
 * @Description:
 * @CreateDate: 2018/8/8 10:36
 */
public class ExcelUtil {

    /**
     * 导出Excel
     * @param sheetName sheet名称
     * @param wb HSSFWorkbook对象
     * @return
     */
    //String[] firstTitle, String []title,String [][]values
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, Map<String, Map<String, Object>> map, HSSFWorkbook wb,int firstRowNum){
        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        if(wb == null){
            wb = new HSSFWorkbook();
        }

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.getSheet(sheetName);
        if(null == sheet){
            sheet = wb.createSheet(sheetName);
        }

        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(firstRowNum);

        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        setStyle(style);
        int d = 0;
        for(int i = 0; i < map.size(); i++){
            Map<String, Object> maps = map.get((i+1) + "");
            Set<Map.Entry<String, Object>> set = maps.entrySet();
            String[][] content = null;
            for(Map.Entry<String, Object> ent : set){
                if(ent.getKey().contains("title")){
                    //创建标题
                    String[] sa = new String[1];
                    if(ent.getKey().equals("title1")){
                        d+=firstRowNum;
                        sa[0] = String.valueOf(ent.getValue());
                    }else{
                        sa = (String[])ent.getValue();
                        String s = sa.toString();
                    }
                    createTitle(sa, row, sheet, style, d, true);
                    if(d == 0){
                        //合并单元格
                        cellRange(sheet, d, d, 0, 6);
                    }else if( d == 4){
                        //合并单元格
                        cellRange(sheet, d, d, 0, 7);
                    }
                }else if(ent.getKey().contains("content")){
                    //创建内容
                    content = (String[][])ent.getValue();
                    createText(content, row, sheet, style, d);
                }
                d++;
            }
        }
        return wb;
    }

    /**
     * 设置单元格样式
     * @param style
     */
    public static void setStyle(HSSFCellStyle style){
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        //设置单元格的边框
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
    }

    /**
     * 合并单元格
     * @param sheet
     */
    public static void cellRange(HSSFSheet sheet, int sline, int eline, int scolumn, int ecolumn){
        //合并单元格
        CellRangeAddress region = new CellRangeAddress(sline, eline, (short) scolumn, (short) ecolumn); //参数1：起始行 参数2：终止行 参数3：起始列 参数4：终止列
        sheet.addMergedRegion(region);
    }

    /**
     * 创建标题
     * @param title 标题数组
     * @param row
     * @param sheet
     * @param style 单元格样式
     * @param rownum 行标
     */
    public static void createTitle(String []title, HSSFRow row, HSSFSheet sheet, HSSFCellStyle style, int rownum, boolean widthFlag){
        //创建标题
        if(rownum != 0){
            row = sheet.createRow(rownum);
        }
        if(null != title){
            HSSFCell cell = null;
            if(title.length <= 1){
                if(row.getRowNum() < 3){
                    for (int i = 0; i < 7; i++) {
                        cell = row.createCell(i);
                        cell.setCellStyle(style);
                        cell.setCellValue(title[0]);
                        if(widthFlag){
                            columnWidth(sheet ,i);
                        }
                    }
                }else{
                    for (int i = 0; i < 8; i++) {
                        cell = row.createCell(i);
                        cell.setCellStyle(style);
                        cell.setCellValue(title[0]);
                        if(widthFlag){
                            columnWidth(sheet ,i);
                        }
                    }
                }
            }else{
                for(int i=0;i < title.length;i++){
                    cell = row.createCell(i);
                    cell.setCellStyle(style);
                    cell.setCellValue(title[i]);
                    if(widthFlag){
                        columnWidth(sheet ,i);
                    }
                }
            }
        }
    }

    /**
     * 设置自适应列宽
     * @param sheet
     * @param index
     */
    public static void columnWidth(HSSFSheet sheet, int index){
        //设置自适应列宽
        sheet.autoSizeColumn(index);
        sheet.setColumnWidth(index,sheet.getColumnWidth(index)*17/10);
    }

    /**
     * 创建内容
     * @param values 内容数组
     * @param row
     * @param sheet
     * @param style 单元格样式
     * @param rownum 行标
     */
    public static void createText(String [][]values, HSSFRow row, HSSFSheet sheet, HSSFCellStyle style, int rownum){
        //创建内容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + rownum);
            //设置自适应列宽
            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(i,sheet.getColumnWidth(i)*17/10);
            for(int j=0;j<values[i].length;j++){
                //将内容按顺序赋给对应的列对象
                HSSFCell cell = row.createCell(j);
                cell.setCellStyle(style);
                cell.setCellValue(values[i][j]);
            }
        }
    }

    //下载
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
